<template>
  <div class="createPost-container">
    <el-form v-if="!infoLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="200px">
      <div class="createPost-main-container">
        <el-form-item v-if="!readOnly" label="用户名" prop="realName">
          <template>
            {{ postForm.username }}
          </template>
        </el-form-item>
        <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
          <el-table-column width="195px" prop="dept_name" label="菜单名称" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.isLeaf?'——':'' }}{{ scope.row.menuName }}
            </template>
          </el-table-column>
          <el-table-column align="left" label="操作" min-width="200">
            <template slot-scope="scope">
              <el-checkbox-group v-if="scope.row.menuActions" v-model="setActions">
                <el-checkbox v-for="(item,index) in scope.row.menuActions.split(',')" :key="scope.row.id*100+index" :label="scope.row.id+'|'+item" @change="changeMyList(scope.$index)">{{ roleId2Name(item) }}</el-checkbox>
              </el-checkbox-group>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item v-if="!readOnly" style="margin: 20px 0;">
          <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>

const defaultForm = {
  username: '',
  password: '',
  repetPassword: '',
  realName: '',
  deptId: '',
  sysRoleId: '',
  postName: '',
  email: '',
  phone: '',
  userEnabled: '',
  id: null
}

export default {
  name: 'ArticleDetail',
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    infoid: {
      type: Number,
      default: 0
    },
    timestamp: {
      type: Number,
      default: 0
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      setActions: [],
      actionList: [],
      list: [],
      listLoading: false,
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      deptOption: [],
      roleOption: [],
      rules: {
        username: [{ validator: validateRequire }],
        realName: [{ validator: validateRequire }],
        deptId: [{ validator: validateRequire }],
        postName: [{ validator: validateRequire }],
        email: [{ validator: validateRequire }],
        phone: [{ validator: validateRequire }],
        userEnabled: [{ validator: validateRequire }]
      },
      tempRoute: {}
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        this.setActions = []
        console.log('timestamp:' + val)
        this.getData(this.infoid)
        this.getAuth(this.infoid)
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
  },
  created() {
    this.getMenus()
    this.getActionList()

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    changeMyList(index) { // 解决点击响应不同步的问题
      const tmpObj = this.list[index]
      this.$set(this.list, index, tmpObj)
    },
    roleId2Name(id) {
      const item = this.actionList.find(item => item.value === id)
      if (item && item.label) {
        return item.label
      }
    },
    getData(id) {
      this.infoLoading = true
      if (id) {
        this.$http
          .get('/api/sysUser/getPersonalInfoById?id=' + id)
          .then(response => {
            this.infoLoading = false
            if (response.data.success === true) {
              this.postForm = response.data.result
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
          })
      } else {
        this.$nextTick(() => {
          this.infoLoading = false
        })
        this.postForm = Object.assign({}, defaultForm)
        this.imageUrl = ''
      }
    },
    getAuth(id) {
      this.listLoading = true
      if (id) {
        this.$http
          .get('/api/sysAuth/getAuthByUser?userId=' + id)
          .then(response => {
            this.listLoading = false
            if (response.data.success === true) {
              this.setActions = []
              for (const item of response.data.result) {
                this.setActions.push(item.sysMenuId + '|' + item.actionType)
              }
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.listLoading = false
          })
      } else {
        this.$nextTick(() => {
          this.listLoading = false
        })
      }
    },
    getMenus() {
      this.$http
        .get('/api/sysMenu/getMenuList')
        .then(response => {
          this.listLoading = false
          if (response.data.success === true) {
            this.list = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.listLoading = false
        })
    },
    getActionList() {
      this.$http
        .get('/api/sysDict/getByCode?code=03')
        .then(response => {
          if (response.data.success === true) {
            this.actionList = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    submitForm() {
      const actions = []
      for (const item of this.setActions) {
        actions.push({ menuId: item.split('|')[0], actionType: item.split('|')[1] })
      }
      const para = {
        authList: actions,
        userId: this.infoid
      }
      this.loading = true
      this.$http
        .post('/api/sysAuth/saveAuth', para)
        .then(response => {
          this.loading = false
          if (response.data.success === true) {
            this.$message({
              message: '提交成功，该用户下次登录系统时生效',
              type: 'success'
            })
            this.$emit('dialogHide')
          } else {
            console.log('提交失败:' + response.data.message)
            this.$message({
              message: '提交失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(function(error) {
          console.log(error)
          this.loading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    // padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
